package org.yufan.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.yufan.admin.bean.PicUploadResult;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;

import java.io.IOException;
import java.util.UUID;

/**
 * Created by zxd on 2018/3/26.
 */
@Controller
@RequestMapping("/pic")
public class UploadController {

    private Logger LOGGER= LoggerFactory.getLogger(UploadController.class);

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public PicUploadResult upload(@RequestParam  MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        //上传图片的路径
        String path="E://image";
        LOGGER.info("上传图片的路径{}",path);
        //获取文件的后缀
        String filename=uploadFile.getOriginalFilename();

        LOGGER.info("filename is {}",filename);
        String end=filename.substring(filename.lastIndexOf("."));

        LOGGER.info("the file end is {}",end);
        //生成新的文件名
        String uuid_name= UUID.randomUUID().toString().replace("-","")+end;
        File file=new File(path+ File.separator+uuid_name);
         LOGGER.info("生成的文件名是{}",uuid_name);
        //保存图片到磁盘
        uploadFile.transferTo(file);
        //封装结果集对象，返回json的响应数据
        PicUploadResult picUploadResult=new PicUploadResult();
        //上传成功的状态
        picUploadResult.setError(0);
        //设置上传图片的路径
        picUploadResult.setUrl("http://image.yufan.com/"+uuid_name);
        //读取图片


        BufferedImage image= ImageIO.read(file);
        if(image!=null){
            picUploadResult.setWidth(image.getWidth()+"");
            picUploadResult.setHeight(image.getHeight()+"");
            LOGGER.debug("上传成功!");
        }else{
            //上传失败
            picUploadResult.setError(1);
            if(file.exists()){
                file.delete();
            }
            LOGGER.error("上传失败,上传的文件名是{},上传者的ip地址是{}",filename,request.getRemoteAddr());
        }
        return picUploadResult;
    }

}
